package frontend;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;

import model.SearchForm;

import org.apache.catalina.websocket.MessageInbound;
import org.apache.catalina.websocket.StreamInbound;
import org.apache.catalina.websocket.WebSocketServlet;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.JSONValue;

import db.Item;

import util.DBUtil;
import util.FormUtil;

@WebServlet("/searchWs")
public class SearchWebSocket extends WebSocketServlet{
    
    /**
     * 
     */
    private static final long serialVersionUID = 1L;

    @Override
    protected StreamInbound createWebSocketInbound(String arg0, HttpServletRequest arg1) {
        return new MessageInbound() {
	    
	    @SuppressWarnings("unchecked")
	    @Override
	    protected void onTextMessage(CharBuffer arg0) throws IOException {
		 String recievedMessage = arg0.toString();
		 JSONObject o = (JSONObject) JSONValue.parse(recievedMessage);
		 Map<String, String[]> parameterMap = new HashMap<String, String[]>();
		 for(Object key : o.keySet()){
		     parameterMap.put(key.toString(), new String[]{o.get(key).toString(),""});
		 }
		 SearchForm form = FormUtil.getSearchFormFromRequestMap(parameterMap);
		 DBUtil dbUtil = new DBUtil();
		 List<Item> items;
		 if(o.get("catalog") != null){
		    items = dbUtil.searchItems(form, o.get("catalog").toString());
		 }else{
		     items = dbUtil.searchItems(form, null);
		 }
		 if(items != null && items.size() > 0){
		     JSONArray array = new JSONArray();
		     for(Item i : items){
			 JSONObject item = new JSONObject();
			 item.put("name", i.getName());
			 item.put("id", i.getItem());
			 item.put("description", i.getDescription());
			 item.put("sale_price", i.getSalePrice());
			 item.put("store_price", i.getStorePrice());
			 item.put("producer", i.getProducer());
			 item.put("muuda", i.getItem());
			 item.put("ladu", i.getItem());
			 array.add(item);
		     }
		     CharBuffer b = CharBuffer.wrap(JSONValue.toJSONString(array));
			getWsOutbound().writeTextMessage(b);
		 }else{
		     getWsOutbound().writeTextMessage(CharBuffer.wrap("no_record"));
		 }
		 	
		 
		 System.out.println(form.getName());
		
	    }
	    
	    @Override
	    protected void onBinaryMessage(ByteBuffer arg0) throws IOException {
		// TODO Auto-generated method stub
		
	    }
	};
    }

}
